<script lang="ts" setup>
import { ref, onMounted, computed, watch, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import jyglService from '@/api/jygl'
import zzjgService from '@/api/zzjg'
import formBox from '@/components/queryTable/form/index.vue'
import tableBox from '@/components/queryTable/table/index.vue'
import { formItems } from '../form-item'
import lcgzDialog from '@/views/daly/jygl/dialogs/lcgz-dialog.vue'
import jydDialog from '@/views/daly/jygl/dialogs/jyd-dialog.vue'
import wdsqdYsqDialog from '../dialogs/wdsqd-jysq-dialog.vue'
import { TableItem } from '@/api/common'
import { JyglListQueryResult, JysqajxxlbQueryResult, JysqspdalbQueryResult } from '@/api/jygl-dto'
import TreeUtilDTO from '@/utils/tree'

const emit = defineEmits(['addTab'])
const loading = ref<boolean>(false)
const wdsqdYsqDialogRef = ref()
const rightSmall = ref<boolean>(true)
const dragFlag = ref<boolean>(false)
const moveLenHeight = ref<number>(0)
const activeDalx = ref()
/**
 * 数据源
 */
const optionsObjs = ref<any>({})

// 更多条件查询
const formLabel = ref()
onMounted(async () => {
  // 分页
  loading.value = true
  zzjgService.queryAllOrg({}).then((res: any) => {
    optionsObjs.value.sjdwbm = TreeUtilDTO.getTreeData(res.data || [], 'dwbm', 'fdwbm')
  })
  formLabel.value = await formItems('jyd')
  loading.value = false
  changePageNum(1)
})

// 借阅-查询待调档分页列表
const total = ref<number>(0)
const page = computed(() => {
  return {
    pageNum: form.value.pageNum,
    pageSize: form.value.pageSize,
    total: total.value,
  }
})

/*
 * 分页
 */
const changePageNum = (val: number) => {
  form.value.pageNum = val
  getTableData()
}

/*
 * 分页
 */
const changePageSize = (val: number) => {
  form.value.pageNum = 1
  form.value.pageSize = val
  getTableData()
}

/*
 * 查询按钮
 */
const searchTable = (data: any) => {
  let newObj: any = {}
  for (const key in data) {
    if (key.endsWith('-rq')) {
      const kssj = key.replace('-rq', 'ksrq')
      const jssj = key.replace('-rq', 'jsrq')
      if (data[key]?.length) {
        newObj[kssj] = data[key][0]
        newObj[jssj] = data[key][1]
      } else {
        newObj[kssj] = ''
        newObj[jssj] = ''
      }
    }
    newObj[key] = data[key]
  }

  if (newObj['jydalxdms']?.length === 0) {
    newObj['jydalxdms'] = undefined
  }
  form.value.filter = newObj
  getTableData()
}

// 查询条件
const form = ref({
  pageNum: 1, // 页码
  pageSize: 20, // 页容量
  filter: {
    jydbh: '', // 借阅单编号
    sqksrq: '', // 申请开始日期
    sqjsrq: '', // 申请结束日期
    sjdwbm: undefined, // 数据所属单位编码
    jydalxdms: undefined, // 借阅档案类型代码
    jylxdm: '', // 借阅类型代码
    jyfsdm: '', // 借阅方式代码
    jymddm: '', // 借阅目的代码
    cxdanr: '', // 查询档案内容
    jyztdm: '', // 借阅状态代码
  }, // 过滤Dto对象
})

/*
 * 获取表格数据
 */

const tableBoxRef = ref<InstanceType<typeof tableBox>>()
// 表格数据
const tableData = ref<TableItem>({
  data: [],
  titles: [
    {
      label: '借阅单编号',
      prop: 'jydbh',
      width: 200,
      custom: false,
      sort: true,
      dqfs: 'left',
    },
    { label: '申请日期', prop: 'sqrq', width: 130, dqfs: 'left' },
    { label: '档案所属院', prop: 'sjdwmc', width: 120, dqfs: 'left' },
    { label: '档案类型', prop: 'jydalxList', width: 120, dqfs: 'left', specialdalx: true },
    { label: '借阅类型', prop: 'jylxmc', width: 120, dqfs: 'left' },
    { label: '借阅方式', prop: 'jyfsmc', width: 120, dqfs: 'left' },
    { label: '借阅天数', prop: 'jyts', width: 120, dqfs: 'left' },
    { label: '借阅目的', prop: 'jymdmc', width: 150, dqfs: 'left' },
    { label: '借阅明细', prop: 'jymx', width: 120, dqfs: 'left' },
    { label: '借阅状态', prop: 'jyztmc', width: 150, dqfs: 'left', shzt: true },
    { label: '审批通过日期', prop: 'sptgrq', width: 160, dqfs: 'left' },
    { label: '借阅剩余天数', prop: 'jysytl', width: 160, dqfs: 'left' },
    { label: '归还日期', prop: 'ghrq', width: 120, dqfs: 'left' },
  ],
})

const getTableData = () => {
  const params = form.value
  jyglService
    .queryJydList(params as any)
    .then((res) => {
      tableData.value.data = res.data.list
      total.value = res.data.total
      ssdaList.value = []
      spdaList.value = []
      selectRow.value = undefined
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
}

/**
 * 表格选择
 */
const selectRow = ref<any>()
const selectionChange = (val: any[], row: any) => {
  if (val.length > 0) selectRow.value = row
  else selectRow.value = undefined

  if (val.length > 1) {
    const delChecked = val.shift()
    tableBoxRef.value?.refTable.toggleRowSelection(delChecked, false)
  }
}
const selectAllChange = () => {
  nextTick(() => {
    if (selectRow.value) {
      selectRow.value = undefined
      tableBoxRef.value?.refTable.clearSelection()
    } else {
      selectRow.value = tableData.value.data[0]
      tableBoxRef.value?.refTable.clearSelection()
      tableBoxRef.value?.refTable.toggleRowSelection(selectRow.value, true)
    }
  })
}

// 点击撤回申请
const recallChsq = () => {
  ElMessageBox.confirm('是否撤回申请', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    const params = {
      jysqbh: selectRow.value?.jysqbh,
    }
    jyglService
      .recallJysq(params)
      .then((res) => {
        if (res.data.czjg) {
          ElMessage.success('撤回成功')
          getTableData()
        } else {
          ElMessage.error(res.message)
        }
      })
      .catch((err) => {
        !err.isError && ElMessage({ type: 'warning', message: err.message })
      })
  })
}

/*
 * 提交借阅
 */
const submitJy = () => {
  ElMessageBox.confirm('是否提交借阅', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    const params = {
      jysqbh: selectRow.value?.jysqbh,
    }
    jyglService
      .createJylc(params)
      .then(() => {
        ElMessage.success('提交成功')
        getTableData()
      })
      .catch((err) => {
        !err.isError && ElMessage({ type: 'warning', message: err.message })
      })
  })
}

// 修改借阅申请
const editJysq = () => {
  wdsqdYsqDialogRef.value.openDialog('edit', '诉讼档案', selectRow.value)
}

// 续借申请
const submitXj = () => {
  wdsqdYsqDialogRef.value.openDialog('add', '诉讼档案', selectRow.value)
}

/*
 * 查看借阅单下的诉讼档案
 */
const ssdaList = ref<JysqajxxlbQueryResult[]>([])
const querySsdaList = (row: JyglListQueryResult) => {
  const params = { jysqbh: row.jysqbh }
  jyglService
    .queryJysqajxxlb(params)
    .then((res) => {
      ssdaList.value = res.data
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
}

/*
 * 查看借阅单下的视频档案
 */
const spdaList = ref<JysqspdalbQueryResult[]>([])
const querySpdaList = (row: JyglListQueryResult) => {
  const params = { jysqbh: row.jysqbh }
  jyglService
    .queryJysqspdalb(params)
    .then((res) => {
      spdaList.value = res.data
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
}

const rowClickData = ref()
// 展示下方档案区域
const showDa = ref(false)
const rowClick = (row: JyglListQueryResult) => {
  querySsdaList(row)
  querySpdaList(row)
  rowClickData.value = row
  expandRowKeys.value = []
  showDa.value = true
}

/*
 * 拖拽事件
 */
// 初始距离
// 是否按下
const dragstart = () => {
  dragFlag.value = true
}
const dragRight = (e: any) => {
  if (!dragFlag.value || !e.clientY) {
    return
  }
  if (e.clientY && window.innerHeight - e.clientY - 26 <= 280) {
    moveLenHeight.value = 280
  } else if (e.clientY && window.innerHeight - e.clientY - 26 >= 400) {
    moveLenHeight.value = 400
  } else {
    moveLenHeight.value = window.innerHeight - e.clientY - 26
  }
}

const dragend = () => {
  dragFlag.value = false
}

/*
 * 校验能否查看档案详情
 */
const validateViewLimit = (row: any, dalx: string) => {
  const params = { jysqbh: row.jysqbh }
  jyglService
    .getDasfkyck(params)
    .then((res) => {
      if (res.data.boo) {
        emit('addTab', {
          ...row,
          fldm: activeDalx.value === 'ssda' ? 1 : 31,
          dalx: dalx,
          showDownloadPrinting: true,
        })
      } else {
        ElMessage.warning('借阅申请未审批通过，暂不允许查看！')
      }
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
}
// 查看档案详情
const viewDaxq = (row: any, dalx: string) => {
  validateViewLimit(row, dalx)
}

const treeData = ref()

const expandRowKeys = ref()
// 展开
const expandChange = (expandedRows: { ajbh: string }, rowList: any) => {
  if (rowList.length) {
    expandRowKeys.value = []
    if (expandedRows) {
      expandRowKeys.value.push(expandedRows.ajbh)
    }
  } else {
    expandRowKeys.value = []
  }
  queryJycajwsmlsj(expandedRows, rowList)
}

/*
 * 查询借阅车诉讼目录
 */
const queryJycajwsmlsj = (expandedRows: any, rowList: any) => {
  const list = rowList.find((item: any) => item.ajbh === expandedRows.ajbh)
  if (list) {
    const params = {
      ajbh: expandedRows.ajbh as string,
      jysqbh: rowClickData.value.jysqbh as string,
      mlxslx: '0',
    }
    jyglService
      .queryJyqsajmlList(params)
      .then((res) => {
        treeData.value = TreeUtilDTO.getTreeData(res.data, 'bh', 'fbh')
      })
      .catch((err) => {
        !err.isError && ElMessage({ type: 'warning', message: err.message })
      })
  }
}

/*
 * 打开流程跟踪弹窗
 */
const lcgzRef = ref()
const viewLcgz = (row: any) => {
  lcgzRef.value?.openDialog(row)
}

/*
 * 打开借阅单弹窗
 */
const jydRef = ref()
const viewJyd = (row: any) => {
  jydRef.value?.openDialog(row.jysqbh)
}

watch(
  () => [ssdaList.value.length, spdaList.value.length],
  (val) => {
    if (val[0] > 0) {
      activeDalx.value = 'ssda'
    } else if (val[1] > 0) {
      activeDalx.value = 'spda'
    } else {
      activeDalx.value = 'ssda'
    }
  },
)
</script>
<template>
  <div class="container" v-loading="loading">
    <div class="content-box">
      <!--表单-->
      <div class="form-box">
        <form-box
          ref="formBoxRef"
          :formLabel="formLabel"
          :formData="form.filter"
          :moreShow="false"
          :optionsObj="optionsObjs"
          @searchEvent="searchTable"
        />
      </div>
      <!--按钮组-->
      <div class="btn-box">
        <!-- <div class="table-title">
          <span>退改审批</span>
        </div> -->
        <button
          class="btn_operation"
          @click="recallChsq"
          :disabled="
            !selectRow ||
            selectRow.jyztdm === 'gd0450001' ||
            selectRow.jyztdm === 'gd0450006' ||
            selectRow.jyztdm === 'gd0450009' ||
            selectRow.jyztdm === 'gd0450007' ||
            selectRow.jyztdm === 'gd0450003' ||
            selectRow.jyztdm === 'gd0450008'
          "
        >
          <div class="btn-cx"></div>
          撤回申请
        </button>
        <button
          class="btn_operation"
          @click="editJysq"
          :disabled="
            !selectRow ||
            (selectRow.jyztdm !== 'gd0450001' &&
              selectRow.jyztdm !== 'gd0450003' &&
              selectRow.jyztdm !== 'gd0450007' &&
              selectRow.jyztdm !== 'gd0450009')
          "
        >
          <div class="btn-editxgaj"></div>
          修改
        </button>
        <button
          class="btn_operation"
          @click="submitJy"
          :disabled="
            !selectRow ||
            (selectRow.jyztdm !== 'gd0450001' &&
              selectRow.jyztdm !== 'gd0450003' &&
              selectRow.jyztdm !== 'gd0450007' &&
              selectRow.jyztdm !== 'gd0450009')
          "
        >
          <div class="btn-shtg"></div>
          提交借阅
        </button>
        <button
          class="btn_operation"
          @click="submitXj"
          :disabled="!selectRow || selectRow.jyztdm !== 'gd0450008'"
        >
          <div class="btn-shth"></div>
          续借申请
        </button>
        <button class="btn_operation" @click="changePageNum(1)">
          <div class="btn-refresh"></div>
          刷新
        </button>
      </div>
      <!--表格-->
      <div class="table-box">
        <table-box
          gnbm="jyd"
          ref="tableBoxRef"
          :table-data="tableData"
          :selectShow="true"
          :getTableDataParam="page"
          :tableInfo="{ total: page.total }"
          :highlight-current-row="true"
          @changeCurrent="changePageNum"
          @changeSize="changePageSize"
          @row-click="rowClick"
          @selectChange="selectionChange"
          @select-all-change="selectAllChange"
        >
          <template #myAction>
            <el-table-column label="操作" width="80" fixed="right">
              <template #default="scope">
                <div class="active-img" title="流程跟踪" @click="viewLcgz(scope.row)">
                  <img src="@/assets/images/gdgztext.png" />
                </div>
                <div class="active-img" title="借阅单" @click="viewJyd(scope.row)">
                  <img src="@/assets/images/details.png" />
                </div>
              </template>
            </el-table-column>
          </template>
        </table-box>
      </div>

      <!--拖动div-->
      <div
        v-if="showDa"
        class="table-drag-box"
        :draggable="true"
        title="可上下拖动"
        @dragstart="dragstart()"
        @dragend="dragend()"
        @drag="dragRight($event)"
      >
        <div class="dragImg">
          <el-icon class="dargIcon" color="#bdcae2"><MoreFilled /></el-icon>
        </div>
      </div>
      <div
        v-if="showDa"
        class="right-bottom"
        :class="{ small: !rightSmall }"
        :style="{ height: moveLenHeight ? `${moveLenHeight}px` : '' }"
      >
        <div class="right-img" @click="rightSmall = !rightSmall">
          <img src="@/assets/images/ysq.png" alt="" v-if="!rightSmall" />
          <img src="@/assets/images/zsq.png" alt="" v-else-if="rightSmall" />
        </div>
        <el-tabs class="dsp-tabs" v-model="activeDalx">
          <el-tab-pane
            v-if="ssdaList.length > 0"
            label="&nbsp;&nbsp;&nbsp;&nbsp;诉讼档案&nbsp;&nbsp;&nbsp;&nbsp;"
            name="ssda"
            lazy
          >
          </el-tab-pane>
          <el-tab-pane
            v-if="spdaList.length > 0"
            label="&nbsp;&nbsp;&nbsp;&nbsp;视频档案&nbsp;&nbsp;&nbsp;&nbsp;"
            name="spda"
            lazy
          >
          </el-tab-pane>
        </el-tabs>
        <div class="da-table">
          <el-table
            v-if="activeDalx === 'ssda' && ssdaList.length > 0"
            :data="ssdaList"
            stripe
            :row-key="'ajbh'"
            height="100%"
            @expand-change="expandChange"
            :expand-row-keys="expandRowKeys"
          >
            <template v-if="activeDalx === 'ssda'">
              <el-table-column type="expand">
                <template #default="props">
                  <el-tree
                    style="margin-left: 60px"
                    ref="dalyTreeRef"
                    :data="treeData"
                    :check-strictly="false"
                    :props="{ label: 'mc', children: 'children' }"
                    node-key="dm"
                    highlight-current
                  >
                    <template #default="{ data }">
                      <span class="custom-tree-node">
                        <span>{{ data.mc }} ({{ data.wjsl }})</span>
                      </span>
                    </template>
                  </el-tree>
                </template>
              </el-table-column>
              <el-table-column prop="ajdh" label="档号" min-width="180">
                <template #default="scope">
                  <el-link
                    type="primary"
                    class="custom-link"
                    :underline="false"
                    @click="viewDaxq(scope.row, 'ssda')"
                    >{{ scope.row.ajdh }}</el-link
                  >
                </template>
              </el-table-column>
              <el-table-column prop="ajmc" min-width="200" label="案件名称" />
              <el-table-column prop="bmsah" min-width="300" label="部门受案号" />
              <el-table-column prop="dsrmc" min-width="120" label="当事人" />
              <el-table-column prop="aymc" min-width="160" label="案由" />
              <el-table-column prop="cbjcg" min-width="120" label="检察官" />
              <el-table-column prop="bmmc" min-width="160" label="立卷单位" />
              <el-table-column prop="gdrq" min-width="160" label="归档日期" />
              <el-table-column prop="zzajys" min-width="120" label="文件页数" />
            </template>
          </el-table>
          <el-table
            v-if="activeDalx === 'spda' && spdaList.length > 0"
            :data="spdaList"
            stripe
            :row-key="'id'"
            height="100%"
          >
            <el-table-column prop="dh" label="档号" width="200">
              <template #default="scope">
                <el-link
                  type="primary"
                  class="custom-link"
                  :underline="false"
                  @click="viewDaxq(scope.row, 'spda')"
                  >{{ scope.row.dh }}</el-link
                >
              </template>
            </el-table-column>
            <el-table-column prop="tm" label="题名" />
            <el-table-column prop="splx" label="视频类型" />
            <el-table-column prop="lzz" label="录制者" />
            <el-table-column prop="lzrq" label="录制日期" />
            <el-table-column prop="ljdw" label="立卷单位" />
            <el-table-column prop="gdtgrq" label="归档日期" />
          </el-table>
        </div>
      </div>
    </div>
    <!--修改借阅申请-->
    <wdsqd-ysq-dialog ref="wdsqdYsqDialogRef" @refresh="getTableData" />
    <!-- 流程跟踪 -->
    <lcgzDialog ref="lcgzRef" />
    <!-- 借阅单 -->
    <jydDialog ref="jydRef" />
  </div>
</template>
<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100%;
  background: #fff;
  .content-box {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
  }
  .form-box {
    width: 100%;
  }
  .btn-box {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    margin-bottom: 10px;
  }
  .table-box {
    flex: 1;
    flex-shrink: 0;
    overflow: hidden;
    > .container {
      display: flex;
      flex-direction: column;
    }
  }
  .active-img {
    cursor: pointer;
    float: left;
  }
  .active-img + .active-img {
    margin-left: 10px;
  }
}

.table-drag-box {
  margin-top: 10px;
  flex-shrink: 0;
  height: 13px;
  width: 100%;
  cursor: row-resize;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: row;
  border-top: 1px solid #dae4f1;
  border-bottom: 1px solid #dae4f1;
  .dragImg {
    height: 10px;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    .dargIcon {
      font-size: 29px;
    }
  }
}

.right-bottom {
  height: 280px;
  position: relative;
  overflow-y: auto;
  &.small {
    height: 10px !important;
    border: none !important;
  }
  .right-img {
    z-index: 9;
    cursor: pointer;
    position: absolute;
    left: calc(50% - 4px);
    top: -24px;
    transform: rotate(-90deg);
  }
  .dsp-tabs {
    height: auto;
    border: 0;
    :deep(.el-tabs__content) {
      height: 0;
      padding: 0;
    }
    :deep(.el-tabs__item) {
      // height: 36px;
      padding: 0;
      &:hover,
      &.is-active {
        background-color: transparent;
      }
    }
  }
  .da-table {
    height: calc(100% - 43px);
    padding: 16px 0;
  }
}
</style>
